import {
  getMessageList,
  getList,
  getName,
  getAllOrderNoList,
  getImList,
} from "@/BMViews/api/upload/index.js";
import user from "./user";
// 聊天室
const state = {
  totalList: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  imList:[],
  taskList:[],
  orderList:[],
  messageNum: 0, //全局数量变化
  imUnread: 0, //私聊未读数量
  taskUnread: 0, //任务未读数量
  orderUnread: 0, //订单未读数量
  chatUserList: [], //全局用户列表
  userLists: [], //全局用户列表
  consultTypeList: [],
  projectTypeList: [],
};

// actions
const actions = {
  //获取imList
  async getImLists({commit,dispatch,state}){
    try {
      const {
        code,
        rows
      } = await getImList({type:'0；1'});
      // this.imList = rows;
      console.log(rows,'vuex获取im列表..................');
      let resList = rows;
      resList = await dispatch('addListInfo', resList)
      console.log(resList);
      state.imList = resList
      let unread = resList.reduce((a,b) => a + Number(b.unreadNumber),0);
      dispatch('setUnread',{
        "imUnread": unread
      })
    } catch (err) {
      console.log(err);
    }
  },
  async getTaskLists({commit,dispatch,state}){
    try {
      const {
        code,
        rows
      } = await getImList({type:'01；02', status: 1});
      // this.imList = rows;
      console.log(rows,'vuex获取任务列表..................');
      let resList = rows;
      resList = await dispatch('addListInfo', resList)
      console.log(resList);
      state.taskList = resList
      let unread = resList.reduce((a,b) => a + Number(b.unreadNumber),0);
      dispatch('setUnread',{
        "taskUnread": unread
      })
    } catch (err) {
      console.log(err);
    }
  },
  async getOrderLists({commit,dispatch,state}){
    try {
      const {
        code,
        data
      } = await getMessageList();
      // this.imList = rows;
      console.log(data.rows,'vuex获取订单列表..................');
      let resList = data.rows;
      resList = await dispatch('addListInfo', resList)
      console.log('订单获取',resList);
      state.orderList = resList
      let unread = resList.reduce((a,b) => a + Number(b.unread),0);
      console.log('订单未读',unread);
      dispatch('setUnread',{
        "orderUnread": unread
      })
    } catch (err) {
      console.log(err);
    }
  },
  //补全头像
  addListInfo({ dispatch }, resList){
    return new Promise(async (resolve,reject)=>{
      let userList = [];
      for (let i = 0; i < resList.length; i++) {
        //获取成员信息
        let userIds = resList[i].members?.map(item => {
          if (item.userid != user.state.userId) {
            //如果非自己id为对方id
            resList[i].userPid = item.userid
          }
          return item.userid;
        });
        if (!userIds) {
          // return false
          continue;

        }
        userList = [...userList, ...userIds];
      }
      //去重
      userList = [...new Set(userList)]
      //获取用户数据
      let resUserList = await dispatch('getUserInfo', userList)
      console.log(resUserList);
      resList.forEach(item => {
        let userInfo = resUserList.find(items => item.userPid == items.userId)
        // console.log(userInfo, '111111111111');
        if (userInfo) {
          item.icon = userInfo?.avatar
          if(!item.name){
            item.name = userInfo?.nickName
          }
        }
        let avatarArr = [];
        item.members?.filter(item => {
        	if(item.status != -1){
        		let userInfo = resUserList.find(items=> (items.userId == item.userid))
        		if(userInfo){
        			avatarArr.push(userInfo);
        		}
        	}
        })
        item.avatarArr = avatarArr;
      })
      resolve(resList);
    })
  },
  //获取用户
  getUserInfo({state},name) {
    console.log('用户id组',name);
    return new Promise((resolve,reject)=>{
      getName({userIds: name?.join(',')}).then(res=>{
        if(res.code == 200){
          let data = res.data;
          console.log('获取用户信息', data, state.userLists);
          let userList = state.userLists;
          data.map(item =>{
            let index = userList.findIndex(bc => item.userId === bc.userId)
            if(index == -1){
              userList.push(item)
            }else{
              userList[index] = {
              ...userList[index],
              ...item,
              }
            }
          })
          state.userLists = userList
          console.log('重新生成用户列表',state.userLists);
          //用户列表存入vuex
          resolve(userList);
        }
      })
    })
    // const {
    //   data
    // } = await getName({
    //   userIds: name?.join(',')
    // });
    // let userList = state.chatUserList;
    // data.map(item =>{
    //   ...item,

    // })

  },

  set_chatUserList({commit,state}, data) {
    commit("SET_CHATUSERLIST", data);
  },
  setUnread({commit,state}, data) {
    console.log('vuex',data);
    for(let key in data){
      state[key] = data[key];
    }
    commit("SET_MESSAGENUM");
    // JSON.stringify(data, (key,value) => {
    //   console.log('私聊未读',key);
    //   switch (key) {
    //     case "imUnread":
    //       commit("SET_IMUNREAD", value);
    //       break;
    //     case "taskUnread":
    //       commit("SET_TASKUNREAD", value);
    //       break;
    //     case "orderUnread":
    //       commit("SET_ORDERUNREAD", value);
    //       break;
    //     default:

    //   }
    // });
  },
  addUnread({commit,state}, data) {
    console.log('vuex增加',data);
    for(let key in data){
      state[key] = state[key] + data[key];
    }
    commit("SET_MESSAGENUM");
  },
  subUnread({commit,state}, data) {
    console.log('vuex减少',data);
    for(let key in data){
      state[key] = state[key] - data[key];
      if(state[key] < 0){
        state[key] = 0;
      }
    }
    
    commit("SET_MESSAGENUM");
  },
};

// mutations
const mutations = {
  //显示隐藏
  SET_CHATUSERLIST: (state, data) => {
    state.chatUserList = data;
  },
  //设置私聊数量
  SET_IMUNREAD: (state, data) => {
    state.imUnread = data;
  },
  //设置任务数量
  SET_TASKUNREAD: (state, data) => {
    state.taskUnread = data;
  },
  //设置订单数量
  SET_ORDERUNREAD: (state, data) => {
    state.orderUnread = data;
  },
  //设置订单数量
  SET_MESSAGENUM: (state) => {
    console.log('阅读数',state.imUnread,state.taskUnread,state.orderUnread);
    state.messageNum = state.imUnread + state.taskUnread + state.orderUnread;
    console.log('修改阅读数',state.messageNum);
  },
};
// getters
const getters = {
  messageNum(state) {
    let sum = 0;
    //  去遍历每一项，如果每一项都有消息，则把它们消息的数量相加
    // console.log(this.concatList, "拿不到拿不到");
    state.totalList.forEach((item) => {
      return (sum += item.unread || 0);
    });
    // console.log(totalList, sum, "没有实时");
    return sum;
  },
};
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};
